# coding:utf-8

from django.http import Http404, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from auser.models import User
from movie.models import Movie, Review, Comment
from models import MovieSerializer, ReviewSerializer, UserSerializer, UserDetailSerializer, MCommentSerializer, \
	RCommentSerializer
from api_1.permissions import IsOwnerOrReadOnly
from rest_framework import status, permissions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from rest_framework import mixins
from rest_framework import generics, viewsets


# api_view 一些默认设置初始
from post.models import ReviewComment

# api的根路径 用了viewset就用不上了
@api_view(['GET'])
def api_root(request, format=None):
	return Response({
		'users': reverse('api_1:user-list', request=request, format=format),
		'reviews': reverse('api_1:review-list', request=request, format=format)
	})


@csrf_exempt
def review_load(request):
	if request.method == "GET":
		reviews = Review.objects.all()
		serializer = ReviewSerializer(reviews, many=True)
		return JsonResponse(serializer.data, safe=False)
	elif request.method == "POST":
		# 解析以json方式来的数据
		data = JSONParser().parse(request)
		serializer = ReviewSerializer(data=data)
		if serializer.is_valid():
			serializer.save()
			# serializer.data 数据创建成功后所有数据
			return JsonResponse(serializer.data, status=201)
		return JsonResponse(serializer.errors, status=400)


u"""
响应不再单一的内容类型,向网址添加可选的格式后缀
"""


class ReviewDetail(generics.RetrieveUpdateDestroyAPIView):
	queryset = Review.objects.all()
	serializer_class = ReviewSerializer
	# 必须验证，否则只读，必须本人，才可编辑
	permission_classes = (permissions.IsAuthenticatedOrReadOnly,
	                      IsOwnerOrReadOnly)

	def get(self, request, *args, **kwargs):
		return self.retrieve(request, *args, **kwargs)

	def put(self, request, *args, **kwargs):
		return self.update(request, *args, **kwargs)

	def delete(self, request, *args, **kwargs):
		return self.destroy(request, *args, **kwargs)


# 例如确保在你的view中收到request请求和在response对象中添加context从而能够根据内容协商渲染
@api_view(['GET', 'PUT', "DELETE"])
def review_detail(request, pk, format=None):
	try:
		review = Review.objects.get(pk=pk)
	except Review.DoesNotExist:
		return Response(status=status.HTTP_400_BAD_REQUEST)
	if request.method == "GET":
		serializer = ReviewSerializer(review)
		return Response(serializer.data)
	elif request.method == "PUT":
		serializer = ReviewSerializer(review, data=request.data)
		if serializer.is_valid():
			serializer.save()  # 这调用的是update方法,因为传了实例
			return Response(serializer.data)
		return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
	elif request.method == "DELETE":
		review.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)


class ReviewList(mixins.ListModelMixin,
                 mixins.CreateModelMixin,
                 generics.GenericAPIView):
	queryset = Review.objects.all()
	serializer_class = ReviewSerializer
	permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

	def get(self, request, *args, **kwargs):
		return self.list(request, *args, **kwargs)

	def post(self, request, *args, **kwargs):
		return self.create(request, *args, **kwargs)

	def perform_create(self, serializer):
		serializer.save(owner=self.request.user)


@api_view(['GET', 'POST'])
def reviews_list(request, format=None):
	if request.method == "GET":
		reviews = Review.objects.all()
		serializer = ReviewSerializer(reviews, many=True)
		return Response(serializer.data)
	elif request.method == "POST":
		# 解析以json方式来的数据
		data = JSONParser().parse(request)
		serializer = ReviewSerializer(data=data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data, status=status.HTTP_201_CREATED)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class MovieList(mixins.ListModelMixin,
                mixins.CreateModelMixin,
                generics.GenericAPIView):
	queryset = Movie.objects.all()
	serializer_class = MovieSerializer

	def get(self, request, *args, **kwargs):
		# movies = Movie.objects.all()
		# # many=true用于queryset对象
		# serializer = MovieSerializer(movies, many=True)
		# return Response(serializer.data)
		# self.list是ListModelMixin的list函数
		# 功能是过滤、分页、调用serializer,将数据序列化
		return self.list(request, *args, **kwargs)

	def post(self, request, *args, **kwargs):
		return self.create(request, *args, **kwargs)


class MoviedetailViewset(mixins.RetrieveModelMixin,
                         mixins.UpdateModelMixin,
                         mixins.DestroyModelMixin,
                         generics.GenericAPIView):

	def get(self, request, *args, **kwargs):
		return self.retrieve(request, *args, **kwargs)

	def put(self, request, *args, **kwargs):
		return self.update(request, *args, **kwargs)

	def delete(self, request, *args, **kwargs):
		return self.destroy(request, *args, **kwargs)


class MovieViewset(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.ListModelMixin,
                   viewsets.GenericViewSet):
	serializer_class = MovieSerializer

	def get_queryset(self):
		return Movie.objects.all()

	def list(self, request, *args, **kwargs):
		start = request.GET.get("start", "")
		limit = request.GET.get("limit", "")
		queryset = core_queryset(self, start, limit)
		serializers = self.get_serializer(queryset,many=True)
		return Response(serializers.data, status=status.HTTP_200_OK)


class MCommentViewset(mixins.ListModelMixin,
                      mixins.RetrieveModelMixin,
                      mixins.CreateModelMixin,
                      viewsets.GenericViewSet):
	serializer_class = MCommentSerializer

	def get_queryset(self):
		return Comment.objects.all()

	def list(self, request, *args, **kwargs):
		start = request.GET.get("start","")
		limit = request.GET.get("limit","")
		queryset = core_queryset(self, start, limit)
		serializers = self.get_serializer(queryset,many=True)
		return Response(serializers.data, status=status.HTTP_200_OK)


class RCommentViewset(mixins.ListModelMixin,
                      mixins.RetrieveModelMixin,
                      mixins.CreateModelMixin,
                      viewsets.GenericViewSet):
	serializer_class = RCommentSerializer

	def get_queryset(self):
		return ReviewComment.objects.all()

	def list(self, request, *args, **kwargs):
		start = request.GET.get("start","")
		limit = request.GET.get("limit","")
		queryset = core_queryset(self, start, limit)
		serializers = self.get_serializer(queryset,many=True)
		return Response(serializers.data, status=status.HTTP_200_OK)


class ReviewViewset(mixins.RetrieveModelMixin,
                    mixins.ListModelMixin,
                    viewsets.GenericViewSet):
	serializer_class = ReviewSerializer

	def get_queryset(self):
		return Review.objects.all()

	def list(self, request, *args, **kwargs):
		start = request.GET.get("start","")
		limit = request.GET.get("limit","")
		queryset = core_queryset(self, start, limit)
		serializers = self.get_serializer(queryset,many=True)
		return Response(serializers.data, status=status.HTTP_200_OK)

class UserViewSet(viewsets.ReadOnlyModelViewSet):
	serializer_class = UserDetailSerializer
	queryset = User.objects.all()

	# def get(self, *args, **kwargs):
	# 	print('user')
	# 	return self.list(self.request)

	def list(self, request, *args, **kwargs):
		"""
		?limit=**&&start=**:
		limit:一次返回多少条数据
		start:起始位置
		:return:
		"""
		start = request.GET.get("start","")
		limit = request.GET.get("limit","")
		queryset = core_queryset(self, start, limit)
		serializers = self.get_serializer(queryset,many=True)
		return Response(serializers.data, status=status.HTTP_200_OK)

	def retrieve(self, request, *args, **kwargs):
		return super(UserViewSet, self).retrieve(request, *args, **kwargs)


def core_queryset(self, start, limit):
	print("...",start,"...",limit)
	try:
		start = int(start)
	except ValueError:
		start = 1
	try:
		limit = int(limit)
	except ValueError:
		limit = 0

	try:
		queryset = self.get_queryset().order_by("id")[start - 1:]
	except (IndexError, ValueError):
		queryset = self.get_queryset().order_by('id')
	else:
		if limit <= 0:
			pass
		else:
			try:
				queryset = queryset[:limit]
			except (IndexError, ValueError):
				queryset = queryset[:]

	return queryset


# class ReviewViewSet(viewsets.ModelViewSet):
# 	queryset = Review.objects.all()
# 	serializer_class = ReviewSerializer
# 	permission_classes = (permissions.IsAuthenticatedOrReadOnly,
# 	                      IsOwnerOrReadOnly)
#
# 	def perform_create(self, serializer):
# 		serializer.save(owner=self.request.user)

